import request from '../utils/request';

// API基础路径
const API_BASE_URL = '/api';

// 定义登录参数类型
export interface LoginParams {
    phone: string;
    password: string;
    captchaId: string;
    code: string;
}

// 定义注册参数类型
export interface RegisterParams {
    username: string;
    phone: string;
    password: string;
    confirmPassword: string;
    captchaId: string;
    code: string;
}

// 定义登录响应类型
interface LoginResponse {
    msg: string;
    timeStamp: number;
    code: number;
    tokenInfo?: {
        tokenId: string;
        accessToken: string;
        refreshToken: string;
    };
    ip?: string;
}

// 定义忘记密码参数类型
interface ForgetPassParams {
    email: string;
    password: string;
    confirmPassword: string;
    captchaId: string;
    code: string;
}

// 定义API响应类型
interface ApiResponse<T = any> {
    msg: string;
    timeStamp: number;
    code: number;
    data?: T;
    captchaId?: string;

    [key: string]: any;
}

/**
 * 获取验证码ID
 * @returns Promise 返回验证码ID
 */
export const captchaIdAPI = async (): Promise<string | null> => {
    try {
        // request已经在拦截器中处理了response.data的解析，返回的是res而不是response
        const res = await request.get('/getCaptchaId') as ApiResponse;

        // 使用类型断言处理返回值
        return res.captchaId || null;
    } catch (error) {
        console.error('获取验证码ID请求错误:', error);
        return null;
    }
};

/**
 * 获取验证码图片URL
 * @param captchaId 验证码ID
 * @returns 验证码图片URL
 */
export const captchaImageAPI = (captchaId: string): string => {
    return `${API_BASE_URL}/getCaptchaImage/${captchaId}`;
};

/**
 * 用户登录
 * @param params 登录参数
 * @returns Promise 返回登录结果
 */
export const loginAPI = async (params: LoginParams): Promise<LoginResponse> => {
    try {
        // 使用request进行请求，确保返回的是res.data而不是整个response
        const res = await request.post<LoginResponse>(`/login`, params);

        // 如果response是AxiosResponse，返回其data属性
        if (res && typeof res === 'object' && 'data' in res) {
            return res.data as ApiResponse;
        }

        // 如果response已经是解析过的data (通过request拦截器返回)
        return res as LoginResponse;
    } catch (error) {
        // 详细记录错误信息
        throw error;
    }
};

/**
 * 用户注册
 * @param params 注册参数
 * @returns Promise 返回注册结果
 */
export const registerAPI = async (params: RegisterParams): Promise<ApiResponse> => {
    try {
        const res = await request.post<ApiResponse>('/register', params);

        // 如果response是AxiosResponse，返回其data属性
        if (res && typeof res === 'object' && 'data' in res) {
            return res.data as ApiResponse;
        }

        // 如果response已经是解析过的data (通过request拦截器返回)
        return res as ApiResponse;
    } catch (error) {
        console.error('注册请求失败:', error);
        throw error;
    }
};

/**
 * 退出登录，向后端发送请求
 * @returns Promise 返回登出结果
 */
export const logoutAPI = async (): Promise<ApiResponse> => {
    try {
        // 向后端发送登出请求（使用request拦截器自动添加token）
        return await request.post('/logout') as ApiResponse;
    } catch (error) {
        console.error('登出过程中发生错误:', error);
        throw error;
    }
};

/**
 * 获取登录用户详细信息
 * @returns Promise 返回用户详细信息
 */
export const loginUserInfoAPI = async (): Promise<ApiResponse> => {
    try {
        // 使用request自动添加token，并确保返回类型为ApiResponse
        return await request.get('/getLoginUserInfo') as ApiResponse;
    } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
    }
};

/**
 * 刷新访问令牌
 * @param refreshToken 刷新令牌
 * @returns Promise 返回新的访问令牌
 */
export const refreshAccessTokenAPI = async (refreshToken: string): Promise<ApiResponse> => {
    try {
        const res = await request.get('/getNewAccessToken', {
            headers: {
                'Refresh-Token': refreshToken
            }
        });

        // 如果res是AxiosResponse，返回其data属性
        if (res && typeof res === 'object' && 'data' in res) {
            return res.data as ApiResponse;
        }

        // 如果res已经是解析过的数据 (通过request拦截器返回)
        return res as ApiResponse;
    } catch (error) {
        console.error('刷新令牌请求失败:', error);
        throw error;
    }
};

/**
 * 发送邮箱获取验证码
 * @param email 邮箱地址
 * @returns 返回 captchaId（验证码唯一标识）
 */
export const ForgetPassCaptchaAPI = async (email: string): Promise<ApiResponse> => {
    try {
        return await request.get(`/sendCaptchaToEmail/${email}`);
    } catch (error) {
        console.error('获取验证码失败:', error);
        throw error;
    }
};

/**
 * 修改用户密码
 * @param params 包含email、password、confirmPassword、captchaId、code
 * @returns Promise 返回修改结果
 */
export const editPasswordAPI = async (params: ForgetPassParams): Promise<ApiResponse> => {
    try {
        return await request.post('/editYourPass', params) as ApiResponse;
    } catch (error) {
        console.error('修改密码失败:', error);
        throw error;
    }
};

export default {
    captchaIdAPI,
    captchaImageAPI,
    loginAPI,
    registerAPI,
    logoutAPI,
    loginUserInfoAPI,
    refreshAccessTokenAPI,
    ForgetPassCaptchaAPI,
    editPasswordAPI
};
